<template>
  <u-upload
    ref="upload"
    :action="action"
    :header="header"
    :name="name"
    :max-count="maxCount"
    :width="width"
    :height="height || width"
    :max-size="maxSize * 1024 * 1024"
    :upload-text="uploadText"
    :custom-btn="customBtn"
    :auto-upload="auto"
    :file-list="fileList"
    @on-change="change"
    @on-list-change="change"
    @on-success="onSuccess"
    @on-uploaded="onUpload"
    @on-remove="onRemove"
  >
    <view slot="addBtn">
      <slot name="addBtn" />
    </view>
  </u-upload>
</template>

<script>
//这个组件有个坑，可以上传多张图片，但是file-list参数显示多张图片时，只能显示一张
//如果需要上传多张，可以见我screen-manage-uoload-ad页面的写法，循环渲染多个upload
export default {
  name: "BaseUpload",
  props: {
    maxCount: {
      //最大上传数量
      type: Number | String,
      default: 3,
    },
    width: {
      type: Number | String,
      default: 200,
    },
    maxSize: {
      //限制图片大小多少M
      type: Number | String,
      default: 5,
    },
    uploadText: {
      type: String,
      default: "选择图片",
    },
    auto: {
      type: Boolean,
      default: false,
    },
    height: { type: String | Number, default: 0 },
    fileList: { type: Array, default: [] },
    index: { type: String | Number, default: 0 },
    customBtn: { type: Boolean, default: false },
  },
  computed: {
    action() {
      //return "https://test.51xhkj.com/api/common/imgUpload";

      return this.vSelectSysObj.extra + "/api/common/imgUpload";
    },
    header() {
      return {
        "XX-Token": this.vToken,
        "XX-Device-Type": "wxapp",
        "XX-Api-Version": "1.0.0",
        "XX-Wxapp-AppId": this.vAppId,
      };
    },
  },
  data() {
    return {
      name: "file",
    };
  },
  methods: {
    change(res, name) {
      //非自动上次调用此方法
      if (!this.auto) {
        let uploadUrl = res.map((item) => item.url);
        this.$emit("change", uploadUrl);
      }
    },
    onSuccess(data, i, lists) {
      console.log("success:", data, i, lists);
      if (data.code != 1) {
        uni.showToast({
          title: data.msg || "上传失败~",
          icon: "none",
          mask: true,
          duration: 2000,
        });
        this.$refs.upload.remove(i);
      }
    },
    //自动上传调用此方法
    onUpload(list) {
      console.log("🚀 ~ list", list);
      if (this.auto || list.length > 0) {
        let newList = list.map((item) => item.response.data);
        this.$emit("onUpload", newList, this.index);
      }
    },
    onRemove(i, lists, name) {
      this.onUpload(lists);
    },
    //手动调用
    remove(index) {
      this.$refs.upload.remove(index);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>